#include <iostream>
#include <cstring>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"Thread.hpp"

using namespace MyThread;

int sockfd =0;
std::string server_ip;
uint16_t server_port=0;
pthread_t id;

void Recv()
{
    //收
    while(true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

void Send()
{
    struct sockaddr_in ser;
    memset(&ser, 0, sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_port = htons(server_port);
    ser.sin_addr.s_addr = inet_addr(server_ip.c_str());
    
    const std::string online = "上号";
    sendto(sockfd, online.c_str(), online.size(), 0, (struct sockaddr *)&ser, sizeof(ser));

    while (true)
    {
        std::string input;
        std::cout << "Please Enter# ";
        getline(std::cin, input);

        int n = sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&ser, sizeof(ser));
        (void)n;

        if(input == "quit")
        {
            pthread_cancel(id);
            break;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }

    server_ip = argv[1];
    server_port = std::stoi(argv[2]);

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socket < 0)
    {
        std::cerr << "socket error" << std::endl;
        return 2;
    }

    Thread recv(Recv);
    Thread sd(Send);

    id = recv.GetTid();

    recv.Start();
    sd.Start();

    recv.Join();
    sd.Join();
    return 0;
}